package com.dasberg.gwt.dispatch;

import com.dasberg.gwt.command.Action;
import com.dasberg.gwt.command.Result;
import com.google.inject.Inject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * The actual Action Dispatcher.
 * @author mischa
 */
public class ActionDispatcher implements Dispatcher {
    protected final Map<Class<Action>, Handler<Action>> handlers = new HashMap<Class<Action>, Handler<Action>>();

    @Inject
    public ActionDispatcher(Set<Handler> injectedHandlers) {
        for (Handler<Action> handler : injectedHandlers) {
            handlers.put(handler.getActionClass(), handler);
        }
    }

    /** {@inheritDoc}. */
    public Map<Class<Action>, Handler<Action>> getHandlers() {
        return handlers;
    }

    /** {@inheritDoc}. */
    public Result process(Action action) throws HandlerException, ActionException {
        Handler<Action> handler = handlers.get(action.getClass());
        if (handler == null) {
            throw new HandlerException("No matching handlers found for action " + action.getClass());
        }
        try {
            return handler.process(action);
        } catch (ActionException e) {
            handler.rollback(action);
            throw e;
        }
    }
}

